import com.codezen.helper.Worker;
import com.codezen.util.DownloadHelper;

import flash.events.Event;
import flash.events.ProgressEvent;
import flash.filesystem.File;
import flash.media.Video;

import utils.serials.Episode;

private var dm:DownloadHelper;
private var cachedEp:Episode;

private function initCaching():void{
	dm = new DownloadHelper(File.applicationStorageDirectory.resolvePath('downloads/').nativePath);
	dm.addEventListener(ProgressEvent.PROGRESS, cachingProgress);
	dm.addEventListener(Event.COMPLETE, cachingComplete);
}

private function delCachedEpisode(currentEpisode:Episode):void{
	if(currentEpisode == null) return;
	
	// get filename
	var filename:String = currentEpisode.video;
	filename = filename.substring( filename.indexOf("[[local=")+8, filename.length-2 );
	
	// del file
	var file:File = new File(filename);
	file.deleteFile();
	
	// refresh
	db.addEventListener(Event.COMPLETE, onCacheEventComplete);
	
	// remove from db
	if(currentEpisode.view == "true"){
		currentEpisode.video = String(currentEpisode.video).replace(/\[\[local=(.+?)\]\]/gs,"");
		db.saveEpisode(currentEpisode);
	}else{
		db.delEpisode(currentEpisode);
	}
	
	// refresh
	//dbLoadSaveEpisodes();
}

private function cacheEpisode(ep:Episode):void{
	if(ep == null) return;
	
	cache_wnd.visible = true;
	cache_episode_name.text = "Эпизод: "+ep.title+" [сезон "+ep.season+", эпизод "+ep.num+"]";
	cache_series_name.text = "Сериал: "+ep.serial_title;
	
	// save ep data
	cachedEp = ep;
	
	// get filename
	var res:Array = String(cachedEp.video).split("/");
	var file:String = res[res.length-1];
	
	// download
	dm.downloadFileFromServer(file, cachedEp.video);
}

private function cachingProgress(e:ProgressEvent):void{	
	// get loaded value
	var value:Number = e.bytesLoaded;
	// get total value
	var total:Number = e.bytesTotal;
	// calculate precent
	var precent:Number = Math.round(value*100/total);
	
	// set min-max
	if (cache_progressbar.minimum == 0){
		cache_progressbar.minimum = value;
		cache_progressbar.maximum = total;
	}

	// set progress
	cache_progressbar.label = "Сохранено "+precent+"% ["+
		Number(value/(1024*1024)).toFixed(2)+"мб из "+
		Number(total/(1024*1024)).toFixed(2)+"мб]";
	cache_progressbar.setProgress(value, total);

}

private function cachingComplete(e:Event):void{
	cachedEp.video = cachedEp.video +"[[local="+ dm.localPath + dm.filename+"]]";
	db.addEventListener(Event.COMPLETE, onCacheEventComplete);
	db.saveEpisode(cachedEp);
	
	cache_wnd.visible = false;
}

private function onCacheEventComplete(e:Event):void{
	db.removeEventListener(Event.COMPLETE, onCacheEventComplete);
	// refresh
	dbLoadSaveEpisodes();
}

private function cancelCache():void{
	cache_wnd.visible = false;
	
	adm.cancelDownload();
	dm.cancelDownload();
}